<?php

namespace App\Jobs\QiPao\Group;

use App\Jobs\Job;
use App\Services\Tools\PushService;
use App\Services\Tools\RedisService;
use App\Traits\Elasticsearch;
use Illuminate\Support\Facades\Log;

class GroupMatchPushJob extends Job
{
    protected $userInfo;
    protected $matchUserData;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userInfo, $matchUserData)
    {
        $this->userInfo      = $userInfo;
        $this->matchUserData = $matchUserData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            //Log::info('匹配推送：' . json_encode($this->matchUserData) . json_encode($this->userInfo));
            $userId                              = $this->userInfo['user_id'];
            $matchUserData                       = $this->matchUserData;
            $matchUserAvatar                     = $matchUserData['match_user_avatar'];
            $userMatchInteresting['interesting'] = $this->userInfo['interesting'];

            app('redis')->set('group:match:messageLock:' . $userId . "_" . $matchUserData['user_id'], 1, 'ex', 5, 'nx');
            (new PushService())->groupMatch($matchUserData['user_id'], $userId, $matchUserAvatar, $matchUserData['interesting']);

            if (app('redis')->set('group:match:messageLock:' . $matchUserData['user_id'] . "_" . $userId, 1, 'ex', 5, 'nx')) {
                $userAvatar = RedisService::getUserBaseInfo($userId, 'head_picture');
                (new PushService())->groupMatch($userId, $matchUserData['user_id'], $userAvatar, $userMatchInteresting['interesting']);
            }

            // 脚本更新es文挡  1 延时更新文档的is_match取消匹配状态 2 一天后修改文档的匹配过状态
            //job
            dispatch((new GroupMatchChangeStatusJob($userId, ['is_match' => 0]))->delay(15 * 60));
            if (app('redis')->set('group:match:userDayLock:' . $userId . "_" . date("Y-m-d"), 1, 'ex', 24 * 3600, 'nx')) {

                $tomorrowHour = 24 - date('H');
                dispatch((new GroupMatchChangeStatusJob($userId, ['today_matched' => 0]))->delay($tomorrowHour * 3600));
                Log::info('匹配推送：' . $userId . $tomorrowHour* 3600);
            }

        } catch (\Exception $e) {
            Log::error('匹配推送错误：' . $e->getMessage());
        }
    }

    /* public function fail($exception = null )
     {
         Log::error('giftJob:'.$exception->getMessage());
     }*/
}
